package com.tanhua.admin.listener;

// Log的监听器  处理消息

import com.alibaba.fastjson.JSON;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.db.Log;

import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class LogListener {

    @Autowired
    private LogMapper logMapper;

    @RabbitListener(
            bindings=@QueueBinding(
                    value = @Queue(
                            value = "tanhua.log.queue"
                    ),
            exchange = @Exchange(
                    value = "tanhua.log.exchange",
                    type = ExchangeTypes.TOPIC
            ),
            key="log.*"
    ))
    public void log(String message){

        //解析传过来的数据
        try {
            System.out.println("打印日志:"+message);
            Map<String,String> map = JSON.parseObject(message, Map.class);

            String str = map.get("userId");
            Long userId = Long.valueOf(str);
            String type = map.get("type");
            String logTime = map.get("logTime");

            //构建存入日志表的对象
            Log log=new Log();
            log.setUserId(userId);
            log.setType(type);
            log.setLogTime(logTime);

            logMapper.insert(log);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
